<?php
namespace App\Models;

/**
 * 订单类
 */
class MRemitLog extends BaseModel
{
    public $table = "remit_logs";

    const remit_wait = 0;  //待打款
    const remit_pay = 1;  //已打款
    const remit_yes = 2;    //充值成功
    const remit_no = 3;    //充值失败

    public function user()
    {
        return $this->hasOne(MUser::class, 'id', 'uid');
    }

    /**
     * 验证打款申请数据的合法性
     * $flag 0 = rules  1 = msg
     */
    public static function editRulesWithMsg($flag)
    {
        $rules = array(

            "phone" => "required",
            'money' => "required|numeric",
            'wallet' => "required",
            'remit_type' => 'required',
            'safepass' => 'required',
//            'time' => 'required',
//            'img' => 'required|image',
        );

        $msg = array(
//            "name.required" => "请必须填写真实姓名！",
            "phone.required" => "请必须填写联系方式！",
            "money.required" => "请必须填写打款金额！",
            "wallet.required" => "请必须选择充值钱包！",
//            "time.required" => "请必须填写打款时间！",
            "remit_type.required" => "请必须填写打款方式！",
            "safepass.required" => "请输入交易密码！",
//            "img.required" => "请必须上传打款凭证！",
        );

        if ($flag == 0) {
            return $rules;
        } else {
            return $msg;
        }
    }

    /**
     * 通过打款申请
     * $result = 打款提醒
     */
    public function allow($msg)
    {
        $this->status = self::remit_yes;
        $this->result = $msg;
        $this->deal_time = time();
        return $this->save();
    }

    /**
     * 创建一个打款申请单
     */
    public static function saveRemitLog($request, $user)
    {
        $log = new MRemitLog();
        $log->uid = $user->id;
        $log->no = onlyNo();
        $log->wallet = $request->wallet;
        $log->username = !empty($user->username) ? $user->username : "";
        $log->realname = !empty($user->realname) ? $user->realname : "";
        $log->tel = $request->phone;
        $log->money = $request->money;
        $log->type = $request->remit_type;
        $log->create_time = time();
        $log->status = self::remit_wait;
        if ($request->remit_type == MWallet::$PAY_TYPE_ZFB) {
            $log->zfb = $request->alipay_no;
        } elseif ($request->remit_type == MWallet::$PAY_TYPE_WX) {
            $log->wx = $request->wechat_no;
        } elseif ($request->remit_type == MWallet::$PAY_TYPE_YHK) {
            $log->card_no = $request->bank_no;
            $log->card_name = $request->remitter;
            $log->card_bank = $request->bank_name;
        }
        return $log->save();
    }

    /**
     *拒绝提现
     * $result 拒绝理由
     */
    public function deny($msg)
    {
        //修改状态并补充拒绝缘由
        $this->status = self::remit_no;
        $this->result = $msg;
        $this->deal_time = time();
        return $this->save();
    }
}